/**
 * 目标：实现cookie
 * 问题：不支持中文cookie
 * 解决：通过Buffer转换
 */
const Koa = require('koa')
const app = new Koa()

const Router = require('koa-router')

const index = new Router()
index.get('/', async (ctx, next) => {
  let options = {
    domain: '127.0.0.1',  // 写cookie所在的域名 注意一致
    path: '/',       // 写cookie所在的路径   注意一致
    maxAge: 10 * 60 * 1000, // cookie有效时长
    expires: new Date('2023-02-15'),  // cookie失效时间
    httpOnly: true,  // 是否只用于http请求中获取
    overwrite: false,  // 是否允许重写
    sameSite: 'lax',  //解决samesite问题
  }
  let cookieKey = 'username'
  let cookieValue = '张三'
  /**
   * 通过Buffer解决中文cookie问题
   * new Buffer()弃用 使用 Buffer.from()代替
   */
  // cookieValue = new Buffer(cookieValue).toString('base64') 弃用
  cookieValue = Buffer.from(cookieValue).toString('base64')
  ctx.cookies.set(cookieKey, cookieValue, options)
  ctx.body = 'set cookies ok'
  await next()
})
const user = new Router()
index.get('/user', async (ctx, next) => {
  let cookieValue = ctx.cookies.get('username')
  // value = new Buffer(value, 'base64').toString() 弃用
  cookieValue = Buffer.from(cookieValue, 'base64').toString()
  ctx.body = `<h2>${cookieValue}</h2>`
  await next()
})

const router = new Router()
router.use(index.routes(), index.allowedMethods())
router.use(user.routes(), user.allowedMethods())

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务器在127.0.0.1:3000运行中...')
})